import asyncio


from winsdk.windows.networking.connectivity import NetworkInformation
from winsdk.windows.networking.networkoperators import (
    NetworkOperatorTetheringManager,
    NetworkOperatorTetheringOperationResult,
    TetheringOperationalState,
    NetworkOperatorTetheringAccessPointConfiguration,
)


class HotspotManager:
    def __init__(self, ssid: str, password: str):
        """
        初始化热点管理器

        args:
            - param ssid: 热点的 SSID（名称）
            - param password: 热点的密码
        """

        self.check_ssid_and_password(ssid, password)
        self.ssid = ssid
        self.password = password

        # 获取当前网络连接配置文件
        self.connection_profile = NetworkInformation.get_internet_connection_profile()
        if not self.connection_profile:
            raise Exception("No internet connection profile found.")

        # 创建 TetheringManager 实例
        self.tethering_manager = (
            NetworkOperatorTetheringManager.create_from_connection_profile(
                self.connection_profile
            )
        )
        if not self.tethering_manager:
            raise Exception("Failed to create TetheringManager instance.")

    def check_ssid_and_password(self, ssid: str, password: str, return_: bool = False):
        """
        检查热点名称和密码是否有效
        :param ssid: 热点的 SSID（名称）
        :param password: 热点的密码
        :return: 是否返回结果, 为否则抛出异常
        """
        for i in ssid:
            code = ord(i)
            if code < 32 or code > 126:
                if return_:
                    return False
                else:
                    raise Exception(
                        "SSID contains invalid characters.热点名称包含无效字符"
                    )
        if len(password) < 8:
            if return_:
                return False
            else:
                raise Exception(
                    "Password must be at least 8 characters long.密码长度必须至少为8个字符"
                )
        for i in password:
            code = ord(i)
            if code < 32 or code > 126:
                if return_:
                    return False
                else:
                    raise Exception(
                        "Password contains invalid characters.密码包含无效字符"
                    )
        return True

    async def _start_hotspot_async(self, ssid: str = "", password: str = ""):
        """
        启动热点（异步版本）
        :param ssid: 热点的 SSID（名称）
        :param password: 热点的密码
        :return: True 表示成功，抛出异常表示失败
        """

        if ssid == "":
            ssid = self.ssid
        if password == "":
            password = self.password

        self.check_ssid_and_password(ssid, password)

        # 检查热点是否已开启
        if (
            self.tethering_manager.tethering_operational_state
            == TetheringOperationalState.ON
        ):
            return True  # 热点已启动

        # 配置热点的 SSID 和密码
        configuration = NetworkOperatorTetheringAccessPointConfiguration()
        configuration.ssid = ssid
        configuration.passphrase = password

        # 设置访问点配置
        set_result = await self.tethering_manager.configure_access_point_async(
            configuration
        )

        # 检查并启动热点
        result = await self.tethering_manager.start_tethering_async()
        if result.status == 0:  # 成功
            return True
        else:
            # 如果失败，抛出异常并提供错误代码
            raise Exception(f"Failed to start hotspot. Error code: {result.status}")

    async def _stop_hotspot_async(self):
        """
        停止热点（异步版本）
        :return: True 表示成功，抛出异常表示失败
        """
        # 如果热点已经是关闭状态，直接返回 True
        if (
            self.tethering_manager.tethering_operational_state
            != TetheringOperationalState.ON
        ):
            return True

        # 停止热点
        result = await self.tethering_manager.stop_tethering_async()
        if result.status == 0:  # 成功
            return True
        else:
            raise Exception(f"Failed to stop hotspot. Error code: {result.status}")

    async def _update_hotspot_credentials_async(
        self, ssid: str = "", password: str = ""
    ):
        """
        修改热点的 SSID 和密码（异步版本）
        :param ssid: 新的热点的 SSID（名称）
        :param password: 新的热点的密码
        :return: True 表示成功，抛出异常表示失败
        """

        if ssid == "":
            ssid = self.ssid
        if password == "":
            password = self.password

        # 检查 SSID 和密码的有效性
        self.check_ssid_and_password(ssid, password)

        # 配置热点的新 SSID 和密码
        configuration = NetworkOperatorTetheringAccessPointConfiguration()
        configuration.ssid = ssid
        configuration.passphrase = password

        # 设置访问点配置
        try:
            set_result = await self.tethering_manager.configure_access_point_async(
                configuration
            )

            self.ssid = ssid
            self.password = password
            return True
        except Exception as e:
            raise Exception(f"Failed to update hotspot credentials. Error: {str(e)}")

    def check_hotspot_status(self) -> dict:
        """
        检查热点状态
        :return: 一个字典，包含热点开启状态(is_on)、SSID(ssid) 和密码(password)

        字典的is_on字段为0表示关闭, 1表示开启, 2表示转换中, 3表示未知
        """
        state = self.tethering_manager.tethering_operational_state
        status_dict = {"is_on": False, "ssid": "", "password": ""}
        # 获取当前热点的配置信息
        access_point_config = (
            self.tethering_manager.get_current_access_point_configuration()
        )
        status_dict["ssid"] = access_point_config.ssid
        status_dict["password"] = access_point_config.passphrase

        if state == TetheringOperationalState.ON:
            status_dict["is_on"] = 1
        elif state == TetheringOperationalState.OFF:
            status_dict["is_on"] = 0
        elif state == TetheringOperationalState.IN_TRANSITION:
            status_dict["is_on"] = 2
        elif state == TetheringOperationalState.UNKNOWN:
            status_dict["is_on"] = 3
        else:
            status_dict["is_on"] = 3

        return status_dict

    def start_hotspot(self, ssid: str = "SSID", password: str = "12345678"):
        """
        启动热点（同步版本）
        :param ssid: 热点的 SSID（名称）
        :param password: 热点的密码
        :return: True 表示成功，抛出异常表示失败
        """
        return asyncio.run(self._start_hotspot_async(ssid, password))

    def stop_hotspot(self):
        """
        停止热点（同步版本）
        :return: True 表示成功，抛出异常表示失败
        """
        return asyncio.run(self._stop_hotspot_async())

    async def test(self):
        # 配置热点的新 SSID 和密码
        configuration = NetworkOperatorTetheringAccessPointConfiguration()
        configuration.ssid = "ssid"
        configuration.passphrase = "password"

        # 设置访问点配置
        set_result = await self.tethering_manager.configure_access_point_async(
            configuration
        )

        print(set_result)


if __name__ == "__main__":
    a = HotspotManager("abcd", "12345678")
    asyncio.run(a.test())
